package com.itphy.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.util.Objects;
import java.util.ResourceBundle;

public class RedisClient {
    protected static JedisPool jedispool;
    protected static int EXPIRE = 130;
    static{
        ResourceBundle bundle = ResourceBundle.getBundle("application");
        if (bundle == null) {
            throw new IllegalArgumentException(
                    "[redis.properties] is not found!");
        }

        EXPIRE = Integer.valueOf(bundle.getString("redis.expire"));
        JedisPoolConfig jedisconfig = new JedisPoolConfig();
        jedisconfig.setMaxIdle(Integer.valueOf(bundle
                .getString("redis.pool.maxActive")));
        jedisconfig.setMaxIdle(Integer.valueOf(bundle
                .getString("redis.pool.maxIdle")));
        jedisconfig.setMaxWaitMillis(Long.valueOf(bundle
                .getString("redis.pool.maxWait")));
        jedisconfig.setTestOnBorrow(Boolean.valueOf(bundle
                .getString("redis.pool.testOnBorrow")));
        jedisconfig.setTestOnReturn(Boolean.valueOf(bundle
                .getString("redis.pool.testOnReturn")));
        jedispool = new JedisPool(jedisconfig, bundle.getString("redis.ip"),
                Integer.valueOf(bundle.getString("redis.port")), 100000,bundle.getString("redis.password"));
    }

    public static Jedis getJedis() {
        try {
            return jedispool.getResource();
        } catch (JedisConnectionException jce) {
           return null;
        }
    }

    public void close(Jedis jedis){
        if(!Objects.isNull(jedis)){
            jedis.close();
        }
    }

}
